﻿using Aspose.Cells;
using AWSV2;
using Common.Models;
using Common.Utility;
using NPOI.XSSF.UserModel;
using SUT.PrintEngine.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Windows.Markup;

namespace AWSV2.Views
{
    /// <summary>
    /// WeightListView.xaml 的交互逻辑
    /// </summary>
    public partial class PzReportView
    {
        public Dictionary<string, string> TemplateFieldDic { get; set; } = new Dictionary<string, string>();
        public AppSettingsSection AppSection { get; } = SettingsHelper.AWSV2Settings;
        public Worksheet Worksheet { get; }
        public string WeighingUnit { get; }
        public List<Common.Models.WeighingRecord> WList { get; private set; } //从数据库中查询出的原始称重记录列表
        public DataTable RecordDT { get; private set; } = new DataTable(); //经过转换的称重记录表格，用来显示到列表、导出到excel


        public PzReportView()
        {
            InitializeComponent();
            //初始化数据
            var before1 = DateTime.Now.Date.ToString("yyyy-MM-dd");
            var before2 = DateTime.Now.Date.AddDays(1).ToString("yyyy-MM-dd");

            RecordDT.Columns.Add(new DataColumn("统计时间"));
            RecordDT.Columns.Add(new DataColumn("总毛重"));
            RecordDT.Columns.Add(new DataColumn("总净重"));
            RecordDT.Columns.Add(new DataColumn("总车次"));
            RecordDT.Columns.Add(new DataColumn("称重记录"));
            RecordDT.Columns.Add(new DataColumn("销售过磅"));
            RecordDT.Columns.Add(new DataColumn("采购过磅"));

            WeighingUnit = AppSection.Settings["WeighingUnit"].Value;

            this.Focus();
            this.Deactivated += ShellView_Deactivated;
            //this.Show();
            this.Activate();
        }

        private void ShellView_Deactivated(object sender, EventArgs e)
        {
            //if (!Topmost)
            //{
            //    this.Stop();
            //}
        }

        private void CloseButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Close();
        }


        public void PrintReport()
        {
            if (RecordDT == null)
            {

                return;
            }

            //设置列宽
            var columnWidths = new List<double>();
            for (int i = 0; i < RecordDT.Columns.Count; i++)
            {
                double columnWidth = 70;
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_kh"].Value)
                {
                    columnWidth = 80;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_ch"].Value)
                {
                    columnWidth = 80;
                }
                columnWidths.Add(columnWidth);
            }

            var ht = new AccountHeaderTemplate();
            var headerTemplate = XamlWriter.Save(ht);

            //headerTemplate = headerTemplate.Replace("@StartDate", ((DateTime)StartDate).ToString("yyyy/MM/dd")).Replace("@EndDate", ((DateTime)EndDate).ToString("yyyy/MM/dd"));
            headerTemplate = headerTemplate.Replace("@StartDate", DateTime.Now.ToString("yyyy/MM/dd")).Replace("@EndDate", "").Replace(" ~ ", "");
            headerTemplate = headerTemplate.Replace("@WeighingUnit", WeighingUnit);

            var printControl = PrintControlFactory.Create(RecordDT, columnWidths, headerTemplate);
            printControl.ShowPrintPreview();
        }

        public void ExportReport()
        {
            try
            {
                if (RecordDT == null)
                {

                    return;
                }

                //使用DataTable数据新建excle表格
                Workbook workbook = new Workbook();
                Worksheet worksheet = workbook.Worksheets[0];
                worksheet.Name = "称重统计";

                ImportTableOptions importOptions = new ImportTableOptions();
                importOptions.IsFieldNameShown = true;
                importOptions.IsHtmlString = true;

                worksheet.Cells.ImportData(RecordDT, 0, 0, importOptions);

                #region 增加表头、格式

                Style blodStyle = workbook.CreateStyle();
                blodStyle.Font.IsBold = true;
                StyleFlag flag = new StyleFlag();
                flag.FontBold = true;

                Style headerStyle = workbook.CreateStyle();
                headerStyle.Font.IsBold = true;
                headerStyle.Font.Size = 16;
                headerStyle.HorizontalAlignment = TextAlignmentType.Center;

                worksheet.Cells.Rows[0].ApplyStyle(blodStyle, flag);

                worksheet.Cells.InsertRows(0, 3);

                worksheet.Cells.Merge(0, 0, 1, 8);
                worksheet.Cells["A1"].PutValue("称重统计表");
                worksheet.Cells["A1"].SetStyle(headerStyle);
                worksheet.Cells["A2"].PutValue("统计日期");
                worksheet.Cells["A2"].SetStyle(blodStyle);
                worksheet.Cells.Merge(1, 1, 1, 5);
                worksheet.Cells["B2"].PutValue(DateTime.Now.ToString("yyyy/MM/dd"));
                //worksheet.Cells["B2"].PutValue(((DateTime)StartDate).ToString("yyyy/MM/dd") + " ~ " + ((DateTime)EndDate).ToString("yyyy/MM/dd"));
                worksheet.Cells["G2"].PutValue("重量单位");
                worksheet.Cells["G2"].SetStyle(blodStyle);
                worksheet.Cells["H2"].PutValue(WeighingUnit);

                worksheet.AutoFitColumns();
                #endregion

                workbook.Save(Globalspace._weighingRecordTempPath, SaveFormat.Xlsx);

                //删掉aspose的试用版信息，删掉临时文件
                XSSFWorkbook book;
                using (FileStream file = new FileStream(Globalspace._weighingRecordTempPath, FileMode.Open, FileAccess.Read))
                {
                    book = new XSSFWorkbook(file);
                }
                //book.RemoveSheetAt(1);
                File.Delete(Globalspace._weighingRecordTempPath);

                //打开保存文件对话框，保存称重记录
                var fileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    CreatePrompt = true,
                    OverwritePrompt = true,
                    AddExtension = true,
                    DefaultExt = ".xlsx",
                    Filter = "excel 文件（.xlsx）|*.xlsx",
                    FileName = "称重统计_" + DateTime.Now.ToString("yyyyMMdd"),
                };

                if (fileDialog.ShowDialog().GetValueOrDefault())
                {
                    FileStream file = new FileStream(fileDialog.FileName, FileMode.Create);
                    book.Write(file);
                    file.Close();
                    book.Close();

                }
            }
            catch (Exception e)
            {
                //log.Info($"ExportReport error:{e.Message}");
            }
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            PrintReport();
        }

        private void Button_Click_1(object sender, System.Windows.RoutedEventArgs e)
        {
            ExportReport();
        }
    }
}
